package cn.veliger.springai.service;

import cn.veliger.springai.splitter.CusTextSplitter;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.document.Document;
import org.springframework.ai.reader.TextReader;
import org.springframework.ai.transformer.splitter.TextSplitter;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author veliger
 * create on 2025-06-28
 **/
@Service
@RequiredArgsConstructor
public class DocumentService {

    @Value("classpath:rag/qa.txt")
    private Resource resource;

    private final VectorStore vectorStore;

    public List<Document> loadText() {
        TextReader textReader = new TextReader(resource);
        List<Document> documents = textReader.get();

        TextSplitter textSplitter = new CusTextSplitter();
        List<Document> list = textSplitter.apply(documents);

        for (Document document : list) {
            document.getMetadata().put("author", "veliger");
            document.getMetadata().put("article_type", "blog");
        }

        vectorStore.add(list);

        return list;
    }

    public List<Document> search(String message) {
        SearchRequest searchRequest = SearchRequest
                .builder()
                .query(message)
                .topK(1)
                .similarityThreshold(0.1)
                //.filterExpression("author in ['veliger', 'jill'] && 'article_type' == 'blog'")
                .build();
        return vectorStore.similaritySearch(searchRequest);
    }
}
